﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Mars.Network
{
    /// <summary>
    /// 协议消息处理帮助类
    /// </summary>
    public static class ProtoMessageHandler
    {
        private static readonly ConcurrentDictionary<Type, List<MessageHandler>> MessageHandlerDictionary = new();
        private static readonly List<MessageHandler> EmptyList = new();
        
        public static void AddHandler<T>(Action<T> cb) where T : MessageObject
        {
            var messageType = typeof(T);
            MessageHandlerDictionary.TryGetValue(messageType, out var list);
            if (list == null)
            {
                list = new List<MessageHandler>(2);
                MessageHandlerDictionary.TryAdd(messageType, list);
            }
            
            var messageHandle = new MessageHandler(messageType);
            messageHandle.RegisterHandler(cb);
            list.Add(messageHandle);
        }
        
        /// <summary>
        /// 获取消息处理器
        /// </summary>
        /// <param name="messageType">消息类型</param>
        /// <returns>消息处理器</returns>
        public static List<MessageHandler> GetHandlers(Type messageType)
        {
            if (MessageHandlerDictionary.TryGetValue(messageType, out var list))
            {
                return list?.ToList();
            }

            Debug.LogWarning("没有找到消息处理器消息类型：" + messageType.Name);
            return EmptyList;
        }
    }
}